package com.eshop.modules.quartz.utils;

import com.eshop.config.thread.ThreadPoolExecutorUtil;
import java.util.concurrent.Future;
import com.eshop.utils.ThrowableUtil;
import java.util.concurrent.Callable;
import com.eshop.modules.quartz.domain.QuartzLog;
import com.eshop.modules.quartz.service.QuartzJobService;
import com.eshop.utils.SpringContextHolder;
import com.eshop.modules.quartz.service.QuartzLogService;
import com.eshop.modules.quartz.domain.QuartzJob;
import org.quartz.JobExecutionContext;
import org.slf4j.LoggerFactory;
import java.util.concurrent.ThreadPoolExecutor;
import org.slf4j.Logger;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.quartz.QuartzJobBean;

@Async
public class ExecutionJob extends QuartzJobBean
{
    private Logger logger;
    private static final ThreadPoolExecutor EXECUTOR;
    
    public ExecutionJob() {
        this.logger = LoggerFactory.getLogger((Class)this.getClass());
    }
    
    protected void executeInternal(final JobExecutionContext context) {
        final QuartzJob quartzJob = (QuartzJob)context.getMergedJobDataMap().get("JOB_KEY");
        final QuartzLogService quartzLogService = (QuartzLogService)SpringContextHolder.getBean((Class)QuartzLogService.class);
        final QuartzJobService quartzJobService = (QuartzJobService)SpringContextHolder.getBean((Class)QuartzJobService.class);
        final QuartzLog log = new QuartzLog();
        log.setJobName(quartzJob.getJobName());
        log.setBaenName(quartzJob.getBeanName());
        log.setMethodName(quartzJob.getMethodName());
        log.setParams(quartzJob.getParams());
        final long startTime = System.currentTimeMillis();
        log.setCronExpression(quartzJob.getCronExpression());
        try {
            this.logger.info("任务准备执行，任务名称：{}", quartzJob.getJobName());
            final QuartzRunnable task = new QuartzRunnable(quartzJob.getBeanName(), quartzJob.getMethodName(), quartzJob.getParams());
            final Future<?> future = ExecutionJob.EXECUTOR.submit((Callable<?>)task);
            future.get();
            final long times = System.currentTimeMillis() - startTime;
            log.setTime(times);
            log.setIsSuccess(true);
            this.logger.info("任务执行完毕，任务名称：{} 总共耗时：{} 毫秒", quartzJob.getJobName(), times);
        }
        catch (Exception e) {
            this.logger.error("任务执行失败，任务名称：{}" + quartzJob.getJobName(), (Throwable)e);
            final long times2 = System.currentTimeMillis() - startTime;
            log.setTime(times2);
            log.setIsSuccess(false);
            log.setExceptionDetail(ThrowableUtil.getStackTrace((Throwable)e));
            quartzJob.setIsPause(false);
            quartzJobService.updateIsPause(quartzJob);
        }
        finally {
            quartzLogService.save(log);
        }
    }
    
    static {
        EXECUTOR = ThreadPoolExecutorUtil.getPoll();
    }
}
